package com.boge.modules.house.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.boge.common.utils.R;
import com.boge.modules.house.entity.*;
import com.boge.modules.house.service.*;
import com.boge.modules.sys.entity.SysRoleEntity;
import com.boge.modules.sys.entity.SysUserEntity;
import com.boge.modules.sys.entity.SysUserRoleEntity;
import com.boge.modules.sys.service.SysRoleService;
import com.boge.modules.sys.service.SysUserRoleService;
import com.boge.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class AppController {

    @Autowired
    private TProvinceService provinceService;

    @Autowired
    private TCityService cityService;

    @Autowired
    private TAreaService areaService;



    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    @GetMapping("/province")
    public R getProvince(){
        List<TProvinceEntity> list = provinceService.list();

        return R.ok().put("code",200).put("message","success").put("data",list);
    }

    @GetMapping("/city")
    public R getCity(@RequestParam("provinceCode") String provinceCode){
        List<TCityEntity> list = cityService.listByProvinceCode(provinceCode);

        return R.ok().put("code",200)
                .put("message","success")
                .put("data",list);
    }

    @GetMapping("/area")
    public R getarea(@RequestParam("cityCode") String cityCode){
        List<TAreaEntity> list = areaService.listByCityCode(cityCode);

        return R.ok().put("code",200)
                .put("message","success")
                .put("data",list);
    }





    @PostMapping("/auth/registerApp")
    @ResponseBody
    public R registerApp(@RequestBody SysUserEntity user){
        user.setStatus(1);
        //user.setPassword("123456");
        if(StringUtils.isBlank(user.getNickname())){
            user.setNickname(user.getUsername());
        }

        // 绑定角色
        userService.saveUser(user);
        QueryWrapper<SysRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("role_name","普通用户");
        List<SysRoleEntity> list = roleService.list(wrapper);
        if(list != null && list.size() > 0){
            SysRoleEntity sysRoleEntity = list.get(0);
            SysUserRoleEntity entity = new SysUserRoleEntity();
            entity.setUserId(user.getUserId());
            entity.setRoleId(sysRoleEntity.getRoleId());
            userRoleService.save(entity);
        }
        return R.ok();
    }
}
